package com.xiaochong.tir.apiservice.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.tir.apiservice.component.HbaseBaseQueryComponent;
import com.xiaochong.tir.common.data.hbasepo.BroaderIndex;
import com.xiaochong.tir.common.data.mapper.KLineBroaderIndexMapper;
import com.xiaochong.tir.common.data.po.KLineBroaderIndex;
import com.xiaochong.tir.common.exception.hbase.HbaseCloseExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseConnectionExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseGetTableExcetion;
import com.xiaochong.tir.common.util.CollectionUtil;
import com.xiaochong.tir.common.util.DateUtils;
import com.xiaochong.tir.common.util.HbaseTableUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Project : xc-tir
 * @Package Name : com.xiaochong.tir.apiservice.service
 * @Description : TODO 进行大盘指数和权重相关计算服务
 * @Author : daizhiqing@xiaochong.com
 * @Creation Date : 2018年06月26日下午2:40
 * @ModificationHistory Who When What
 */
@Service
public class HomeIndexKlineService {

    @Autowired
    private HbaseBaseQueryComponent hbaseBaseQueryComponent;


    @Autowired
    private KLineBroaderIndexMapper kLineBroaderIndexDao;

    /**
     * 获取某一天大盘指数数据集合
     * @param dateStr
     * @return
     */
    public JSONArray getBroaderData(String dateStr){
        try {
            String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.HOME_INDEX_EVERY_DAY_RECORDING_TABLE_NAME
                    , HbaseTableUtils.HOME_INDEX_EVERY_DAY_RECORDING_TABLE_FAMILY
                    , HbaseTableUtils.EVERY_DAY_BROADER_INDEX_QUALIFIER
                    , dateStr);

            LogTrace.info("计算大盘日K", "dateStr", dateStr);

            if (StringUtils.isEmpty(data)) {
                LogTrace.info("大盘数据为空", "dateStr", dateStr);
                return null;
            }

            JSONArray jsonArray = JSON.parseArray(data);
            if (CollectionUtil.isBlank(jsonArray)) {
                return null;
            }else{
                return jsonArray;
            }
        }catch (Exception e){
            LogTrace.error(e.getMessage() ,e);
        }
        return null;
    }

    /**
     * 生成大盘指数的日K数据
     * @param dateStr 时间 ： yyyyMMdd
     * @return
     */
    public KLineBroaderIndex createBroaderDayKline(String dateStr){
        try {

            JSONArray jsonArray = getBroaderData(dateStr);
            if(null ==(jsonArray)){return null;}

            boolean isOldDate = true;
            //先查询 防止当前数据重复插入
            KLineBroaderIndex kLineBroaderIndex = new KLineBroaderIndex();
            kLineBroaderIndex.setDate(dateStr);
            kLineBroaderIndex = kLineBroaderIndexDao.selectByEntity(kLineBroaderIndex);
            if(kLineBroaderIndex == null){
                isOldDate = false;
                kLineBroaderIndex = new KLineBroaderIndex();
            }
            int size = jsonArray.size();

            BigDecimal highestPrice = new BigDecimal(0);
            BigDecimal lowestPrice = new BigDecimal(0);

            for (int i = 0; i < size; i++) {
                //大盘指数
                BroaderIndex broaderIndex = jsonArray.getObject(i,BroaderIndex.class);

                if(i == 0){
                    highestPrice = broaderIndex.getBroaderIndex();
                    lowestPrice = broaderIndex.getBroaderIndex();
                    //开盘价
                    kLineBroaderIndex.setOpenPrice(broaderIndex.getBroaderIndex().toString());
                }
                if(i == size -1){
                    //收盘价
                    kLineBroaderIndex.setClosePrice(broaderIndex.getBroaderIndex().toString());
                }
                if(highestPrice.compareTo(broaderIndex.getBroaderIndex())<=0){
                    //最高价
                    highestPrice = broaderIndex.getBroaderIndex();
                }

                if(lowestPrice.compareTo(broaderIndex.getBroaderIndex())>=0){
                    //最低价
                    lowestPrice = broaderIndex.getBroaderIndex();
                }
            }
            kLineBroaderIndex.setHighestPrice(highestPrice.toString());
            kLineBroaderIndex.setLowestPrice(lowestPrice.toString());
            kLineBroaderIndex.setDate(dateStr);
            if(isOldDate){
                kLineBroaderIndexDao.updateByPrimaryKey(kLineBroaderIndex);
            }else {
                kLineBroaderIndexDao.insertSelective(kLineBroaderIndex);
            }
            LogTrace.infoKvs("生成大盘日K数据", "dateStr",dateStr,"kLineBroaderIndex",kLineBroaderIndex.toString());
            return kLineBroaderIndex;
        } catch (Exception e) {
            LogTrace.error(e.getMessage() , e);
        }
        return null;
    }

    /**
     * 获取大盘数据的Ma均线
     * @param days 天数
     * @return
     */
    public BigDecimal getMaDate(int days){
        //获取当前的日期时间
        LocalDateTime dateTime = LocalDateTime.now();

        BigDecimal totalPrice  = new BigDecimal(0);

        for (int i = 1; i <= days; i++) {
            //获取计算的时间
            LocalDateTime dateCalculate = dateTime.minusDays(i);
            String dateStr = DateUtils.dateFormatString(DateUtils.localDateTimeToDate(dateCalculate), DateUtils.format_ymds);

            KLineBroaderIndex kLineBroaderIndex = new KLineBroaderIndex();
            kLineBroaderIndex.setDate(dateStr);

            kLineBroaderIndex = kLineBroaderIndexDao.selectByEntity(kLineBroaderIndex);
            if(kLineBroaderIndex != null){
                totalPrice = totalPrice.add(new BigDecimal(kLineBroaderIndex.getClosePrice()));
            }
        }
        BigDecimal value =  totalPrice.divide(new BigDecimal(days),5,BigDecimal.ROUND_DOWN);
        LogTrace.infoKvs("获取"+days+"Ma均线","totalPrice",totalPrice+"","MaValue" , value.toString());
        return value;
    }

}
